package com.acooly.module.openapi.client.provider.yuejb.utils;

import com.acooly.core.utils.Reflections;
import com.acooly.module.openapi.client.api.anotation.ApiItem;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;

/**
 * Created by ouwen@yiji.com} on 2017/11/7.
 */
@Slf4j
public class DomainObject2Map {
    public static Map<String,String> tomap(Object o){
        Map<String, String> requestData = Maps.newTreeMap();
        try {
            Set<Field> fields = Reflections.getFields(o.getClass());
            String value;
            for (Field fieId : fields) {
                ApiItem apiItem = fieId.getAnnotation(ApiItem.class);
                value = Object2String.convertString(Reflections.invokeGetter(o,fieId.getName()));
                if (null == apiItem) {// 未设置此注解时，加入请求参数
                    requestData.put(fieId.getName(), value);
                } else if (apiItem.sign()) {// 如设置了此注解，需进行判断
                    String itemValue = apiItem.value();
                    if (null == itemValue || "".equals(itemValue)) {// 没有设置注解属性value时即取值字段名
                        requestData.put(fieId.getName(), value);
                    } else {// 否则取值注解属性value的值
                        requestData.put(apiItem.value(), value);
                    }
                }
            }
        } catch (Exception e) {
            log.error("请求报文处理异常：" + e.getMessage());
            return null;
        }
        return requestData;
    }
}
